/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nanosn.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Pattern;

/**
 *
 * @author selkhateeb
 */
public class ClassUtility
{

    public static class CurrentClassGetter extends SecurityManager
    {

        public String getClassName()
        {
            return getClassContext()[1].getName();
        }

        public String getClassSimpleName()
        {
            return getClassContext()[1].getSimpleName();
        }

        public void displayClassesInTheContext()
        {
            for (Class c : getClassContext())
            {
                System.out.println(c.getName());
            }
        }
    }

    public static List<Class> GetAllClassesInJar(String jarFileName)
            throws IOException, ClassNotFoundException
    {
        JarFile jf = new JarFile(jarFileName);
        Enumeration<JarEntry> jarEntry = jf.entries();
        List<Class> result = new ArrayList<Class>();

        while (jarEntry.hasMoreElements())
        {
            String className = jarEntry.nextElement().getName();
            if (isClassNameValid(className))
            {
                String formattedClassName =
                        formatClassNameForClassLoader(className);
                result.add(Class.forName(formattedClassName));
            }
        }

        return result;
    }

    private static boolean isClassNameValid(String className)
    {
        return Pattern.matches("[^$]*\\.class", className);
    }

    private static String formatClassNameForClassLoader(String className)
    {
        //TODO TEST UNDER WINDOWS
        String result = className.replace(File.separator, ".");

        return result.replace(".class", "");
    }
}
